package com.kuang.controller;

import com.kuang.dao.impl.DepartmentDaoImpl;
import com.kuang.dao.impl.EmployeeDaoImpl;
import com.kuang.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDaoImpl employeeDaoImp;

    @Autowired
    private DepartmentDaoImpl departmentDaoImp;

    /**
     * 编辑页面展示
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/user/employee")
    public String updateEmployee(Model model, HttpServletRequest request) {
        String id = request.getParameter("id");
        Employee employee = null;
        if (id != null) {
            employee = employeeDaoImp.getEmployeeById(Integer.parseInt(id));
        }

        model.addAttribute("departmentList", departmentDaoImp.getDeparments());
        model.addAttribute("employee", employee);
        return "update-empl";
    }

    /**
     * 新增、更新数据
     * @param employee
     * @return
     */
    @RequestMapping(value = "/user/add_employee", method = {RequestMethod.POST})
    public String addEmployee(
            Employee employee
    ) {
        if (employee.getId() != null && employeeDaoImp.getEmployeeById(employee.getId()) != null) {
            employeeDaoImp.updateEmployeeById(employee);
        }else {
            employeeDaoImp.save(employee);
        }
        return "redirect:/index";
    }

    /**
     * 删除数据
     * @param id
     * @return
     */
    @RequestMapping(value = "/user/employee_delete")
    public String deleteEmployee(@RequestParam("id") Integer id) {
        employeeDaoImp.removeEmployeeById(id);
        return "redirect:/index";
    }
}
